package com.linkai.多线程._07_gaoji;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description: 测试 Lock 锁
 * @Author: 林凯
 * @Date: 2021/10/19 23:19
 */
public class TestLock {
    public static void main(String[] args) {
        TestLock2 testLock2 = new TestLock2();
        new Thread(testLock2).start();
        new Thread(testLock2).start();
        new Thread(testLock2).start();
    }

}

class TestLock2 implements Runnable {
    int ticketNums = 10;

    // 定义 lock 类
    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            try {
                // 一般放在 try-catch 语句块里面，在 finally 里面进行解锁
                lock.lock();        // 加锁
                if (ticketNums > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(ticketNums--);
                } else {
                    break;
                }
            } finally {
                // 解锁
                lock.unlock();
            }


        }
    }
}
